/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.employee.web;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.CacheUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.StoreSelfProductCategory;
import com.chlitina.store.modules.base.service.StoreSelfProductCategoryService;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.employee.entity.StoreBonusSettingProduct;
import com.chlitina.store.modules.employee.entity.StoreBonusSettingTemplateProduct;
import com.chlitina.store.modules.employee.service.EmployeeService;
import com.chlitina.store.modules.employee.service.StoreBonusSettingProductService;
import com.chlitina.store.modules.sys.utils.DictUtils;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * 产品销售提成设定Controller
 * @author liujiang
 * @version 2013-11-19
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/employee/storeBonusSettingProduct")
public class StoreBonusSettingProductController extends BaseController {

	@Autowired
	private StoreBonusSettingProductService storeBonusSettingProductService;
	@Autowired
	private StoreSelfProductCategoryService storeSelfProductCategoryService;
	@Autowired
	private EmployeeService employeeService;
	
	@ModelAttribute
	public StoreBonusSettingProduct get(@RequestParam(required=false) Long id) {
		if (id != null){
			return storeBonusSettingProductService.get(id);
		}else{
			return new StoreBonusSettingProduct();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(@RequestParam(required=false)String currentSelectId, Long employeeId, Integer type, StoreBonusSettingProduct storeBonusSettingProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
		Employee employee = employeeService.get(employeeId);
		CacheUtils.put("current_bonus_employee", employee);
		Page<StoreBonusSettingProduct> page = storeBonusSettingProductService.find(new Page<StoreBonusSettingProduct>(request, response), employeeId, type); 
        model.addAttribute("page", page);
        model.addAttribute("categoryNameMap", getCategoryNameMap(page.getList()));
        model.addAttribute("type", type);
        model.addAttribute("employee", employee);
        model.addAttribute("currentSelectId", currentSelectId);
		return "modules/employee/storeBonusSettingProductList";
	}
	
	private Map<Long, String> getCategoryNameMap(List<StoreBonusSettingProduct> list) {
		Map<Long, String> categoryNameMap = Maps.newHashMap();
		for (StoreBonusSettingProduct card : list) {
			long l = card.getProduct_type();
			if(l == StoreBonusSettingTemplateProduct.PRODUCT_TYPE_SELF) {
				Long id = card.getProduct_category_id();
				StoreSelfProductCategory template = storeSelfProductCategoryService.get(id);
				categoryNameMap.put(card.getId(), template.getName());
			}
		}
		return categoryNameMap;
	}
	
	@RequestMapping(value = "form")
	public String form(Integer type, StoreBonusSettingProduct storeBonusSettingProduct, Model model) {
		storeBonusSettingProduct.setCard_type(type);
		String categoryName = "";
		long l = storeBonusSettingProduct.getProduct_type();
		if(l == StoreBonusSettingProduct.PRODUCT_TYPE_SELF) {
			long id = storeBonusSettingProduct.getProduct_category_id();
			categoryName = storeSelfProductCategoryService.get(id).getName();
		}
		Map<String, String> sellTypeMap = DictUtils.getDictMap("product_sell_type");
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		List<Long> existId = storeBonusSettingProductService.getExistTemplateId(employee.getId(), StoreBonusSettingProduct.PRODUCT_TYPE_SYS, type);
		for (Long id : existId) {
			if(sellTypeMap.containsKey(id.toString())){
				sellTypeMap.remove(id.toString());
			}
		}
		model.addAttribute("sellTypeMap", sellTypeMap);
		model.addAttribute("storeBonusSettingProduct", storeBonusSettingProduct);
		model.addAttribute("categoryName", categoryName);
		model.addAttribute("employee", employee);
		return "modules/employee/storeBonusSettingProductForm";
	}
	
	@RequestMapping(value = "add")
	public String add(Integer type, StoreBonusSettingProduct storeBonusSettingProduct, Model model) {
		storeBonusSettingProduct.setCard_type(type);
		String categoryName = "";
		long l = storeBonusSettingProduct.getProduct_type();
		if(l == StoreBonusSettingProduct.PRODUCT_TYPE_SELF) {
			long id = storeBonusSettingProduct.getProduct_category_id();
			categoryName = storeSelfProductCategoryService.get(id).getName();
		}
		Map<String, String> sellTypeMap = DictUtils.getDictMap("product_sell_type");
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		List<Long> existId = storeBonusSettingProductService.getExistTemplateId(employee.getId(), StoreBonusSettingProduct.PRODUCT_TYPE_SYS, type);
		for (Long id : existId) {
			if(sellTypeMap.containsKey(id.toString())){
				sellTypeMap.remove(id.toString());
			}
		}
		model.addAttribute("sellTypeMap", sellTypeMap);
		model.addAttribute("storeBonusSettingProduct", storeBonusSettingProduct);
		model.addAttribute("categoryName", categoryName);
		model.addAttribute("employee", employee);
		return "modules/employee/storeBonusSettingProductAdd";
	}
	
	@RequestMapping(value = "addNew")
	public String addNew(String categoryIds, StoreBonusSettingProduct storeBonusSettingProduct, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		int type = storeBonusSettingProduct.getCard_type();
		int btype = storeBonusSettingProduct.getBonus_type();
		float fixed_money = storeBonusSettingProduct.getFixed_money();
		storeBonusSettingProduct.setStore(StoreUtils.getStore());
		storeBonusSettingProduct.setEmployee(employee);
		storeBonusSettingProduct.setBonus_rate(storeBonusSettingProduct.getBonus_rate()/100);
		float bonus_rate = storeBonusSettingProduct.getBonus_rate();
		int pType = storeBonusSettingProduct.getProduct_type();
		List<Long> saveIds = Lists.newArrayList();
		String [] productList = categoryIds.split(",");
		for (int i = 0; i < productList.length; i++) {
			String id = productList[i];
			if (StringUtils.isNotEmpty(id)){
				long productId = Long.parseLong(id);
				saveIds.add(productId);
			}
		}
		for (Long id : saveIds) {
			StoreBonusSettingProduct item = new StoreBonusSettingProduct();
			item.setStore(StoreUtils.getStore());
			item.setEmployee(employee);
			item.setCard_type(type);
			item.setBonus_type(btype);
			item.setFixed_money(fixed_money);
			item.setProduct_type(pType);
			item.setBonus_rate(bonus_rate);
			item.setProduct_category_id(id);
			storeBonusSettingProductService.save(item);
		}
		addMessage(redirectAttributes, "保存产品销售提成设定成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingProduct/?employeeId=" + employee.getId() + "&type=" + type;
	}
	
	@RequestMapping(value = "save")
	public String save(String pageNo, StoreBonusSettingProduct storeBonusSettingProduct, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		String id1 = request.getParameter("product_category_id");
		String id2 = request.getParameter("product_category_id_2");
		long pType = storeBonusSettingProduct.getProduct_type();
		if(pType == StoreBonusSettingTemplateProduct.PRODUCT_TYPE_SYS) {
			storeBonusSettingProduct.setProduct_category_id(Long.parseLong(id1));
		} else {
			storeBonusSettingProduct.setProduct_category_id(Long.parseLong(id2));
		}
		long type = storeBonusSettingProduct.getCard_type();
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		storeBonusSettingProduct.setEmployee(employee);
		storeBonusSettingProduct.setStore(StoreUtils.getStore());
		storeBonusSettingProduct.setBonus_rate(storeBonusSettingProduct.getBonus_rate()/100);
		if (!beanValidator(model, storeBonusSettingProduct)){
			return form(storeBonusSettingProduct.getProduct_type(), storeBonusSettingProduct, model);
		}
		storeBonusSettingProductService.save(storeBonusSettingProduct);
		addMessage(redirectAttributes, "保存产品销售提成设定成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingProduct/?employeeId=" + employee.getId() + "&type=" + type +"&pageNo=" + pageNo +"&currentSelectId=" + storeBonusSettingProduct.getId();
	}
	
	@RequestMapping(value = "delete")
	public String delete(StoreBonusSettingProduct storeBonusSettingProduct, RedirectAttributes redirectAttributes) {
		long employeeId = storeBonusSettingProduct.getEmployee().getId();
		long type = storeBonusSettingProduct.getCard_type();
		storeBonusSettingProductService.delete(storeBonusSettingProduct);
		addMessage(redirectAttributes, "删除产品销售提成设定成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingProduct/?employeeId=" + employeeId + "&type=" + type;
	}

	@RequestMapping(value = "copy")
	public String copy(@RequestParam(required=false) int ifModify, Model model, RedirectAttributes redirectAttributes) {
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		storeBonusSettingProductService.copy(employee, ifModify);
		addMessage(redirectAttributes, "复制模板成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingProduct/?type=0&employeeId=" + employee.getId();
	}
	
	@ResponseBody
	@RequestMapping(value = "storeProductCategoryData")
	public String storeProductCategoryData(@RequestParam(required=false) int type, HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Set<Map<String, Object>> set = Sets.newHashSet();
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		List<Long> existId = storeBonusSettingProductService.getExistTemplateId(employee.getId(), StoreBonusSettingProduct.PRODUCT_TYPE_SELF, type);
		List<StoreSelfProductCategory> categoryList = storeSelfProductCategoryService.findAll();
		for (StoreSelfProductCategory category : categoryList) {
			Long id = category.getId();
			if(existId.contains(id)) {
				continue;
			}
			Map<String, Object> map = Maps.newHashMap();
			map.put("name", category.getName());
			map.put("id", id);
			set.add(map);
		}
		return JsonMapper.getInstance().toJson(set);
	}
}
